package com.minimalist.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author 11987
 */
@Service
public class ImageService {
    private static final Logger log = LoggerFactory.getLogger(ImageService.class);

    /**
     * 使用RestTemplate获取图片并保存到本地
     * 该方法不会抛出异常，确保不会影响Excel数据读取流程
     *
     * @param imageUrl 图片URL
     * @param savePath 保存路径
     * @return 保存的文件路径，如果下载失败则返回null
     */
    public String downloadImage(String imageUrl, String savePath) {
        try {
            RestTemplate restTemplate = new RestTemplate();

            // 设置请求头，模拟浏览器行为
            HttpHeaders headers = new HttpHeaders();
            headers.set("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            headers.set("Accept", "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8");

            HttpEntity<String> entity = new HttpEntity<>(headers);

            // 发送请求获取图片
            ResponseEntity<byte[]> response = restTemplate.exchange(
                    imageUrl,
                    HttpMethod.GET,
                    entity,
                    byte[].class);

            // 保存图片到本地
            Path path = Paths.get(savePath);
            // 确保目录存在
            Path parent = path.getParent();
            if (parent != null && !Files.exists(parent)) {
                Files.createDirectories(parent);
            }
            Files.write(path, Objects.requireNonNull(response.getBody()));

            return savePath;
        } catch (RestClientException e) {
            // 记录HTTP请求异常但不抛出
            log.error("下载图片失败，URL: {}, 错误: {}", imageUrl, e.getMessage());
            return null;
        } catch (IOException e) {
            // 记录文件IO异常但不抛出
            log.error("保存图片失败，路径: {}, 错误: {}", savePath, e.getMessage());
            return null;
        } catch (Exception e) {
            // 捕获其他所有异常
            log.error("图片处理过程中发生未知错误: {}", e.getMessage());
            return null;
        }
    }

    /**
     * 获取图片字节数组
     * 该方法不会抛出异常，确保不会影响其他流程
     *
     * @param imageUrl 图片URL
     * @return 图片字节数组，如果获取失败则返回null
     */
    public byte[] getImageBytes(String imageUrl) {
        try {
            RestTemplate restTemplate = new RestTemplate();

            HttpHeaders headers = new HttpHeaders();
            headers.set("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            headers.set("Accept", "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8");

            HttpEntity<String> entity = new HttpEntity<>(headers);

            ResponseEntity<byte[]> response = restTemplate.exchange(
                    imageUrl,
                    HttpMethod.GET,
                    entity,
                    byte[].class);

            return response.getBody();
        } catch (Exception e) {
            // 记录异常但不抛出
            log.error("获取图片字节失败，URL: {}, 错误: {}", imageUrl, e.getMessage());
            return null;
        }
    }
}

